/*
 * Part of knowledge engineering (ke) course work, 2010/11
 */
package se.bth.ke.firstfriend.web;

import java.lang.String;
import java.util.Map;
import se.bth.ke.firstfriend.dto.MimedAssociationsDTO;
import de.nixis.commons.web.base.Controller;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import se.bth.ke.firstfriend.depend.DataMiner;
import se.bth.ke.firstfriend.depend.AssociationRule;
import se.bth.ke.firstfriend.dto.AssociationRuleDTO;
import se.bth.ke.firstfriend.model.Article;
import static se.bth.ke.firstfriend.util.Util.PRODUCES_HTML;

/**
 *
 * @author nico
 */
@Component
@Path("/dependencies")
public class DependencyController extends Controller {
    
    @PersistenceContext
    private EntityManager em;
    
    @Autowired
    private DataMiner aprioriExecutor;
    
    @GET
    @Transactional
    @Produces(PRODUCES_HTML)
    public Object show(@QueryParam("args") String arguments) {
        Set<AssociationRule> rules = aprioriExecutor.mineAssocitationRules(new HashMap());
        
        MimedAssociationsDTO minedRulesDTO = new MimedAssociationsDTO();
        
        HashMap<Long, Article> cache = new HashMap<Long, Article>() {
            @Override
            public Article get(Object id) {
                Article a = super.get(id);
                
                if (a == null) {
                    a = em.find(Article.class, id);
                    put((Long) id, a);
                }
                
                return a;
            }
        };
        
        for (AssociationRule rule: rules) {
            Set<Article> base = new HashSet();
            for (Long id: rule.getBase()) {
                base.add(cache.get(id));
            }
            
            Article target = cache.get(rule.getTarget());
            
            minedRulesDTO.addAssociationRule(new AssociationRuleDTO(
                target, base, rule.getAssociationAccuracy(), rule.getBaseAccuracy()
            ));
        }
        
        return minedRulesDTO;
    }
 }
